import dayjs, { Dayjs } from "dayjs";
import MonthCalendar from "./MonthCalendar";
import "./index.scss";
import Header from "./Header";
import { CSSProperties, ReactNode, useState } from "react";
import classnames from "classnames";
import LocaleContext from "@/Context/LocaleContext";

export interface CalendarProProps {
	value: Dayjs;
	style?: CSSProperties;
	className?: string | string[];
	// 定期日期显示 完全覆盖原本日期样式
	dateRender?: (currentDate: Dayjs) => ReactNode;
	// 定制日期单元格 内容会被添加到单元格内 不会修改整个样式且在全屏日历模式下才会生效
	dateInnerContent?: (currentDate: Dayjs) => ReactNode;
	// 国际化相关
	locale?: string;
	onChange?: (date: Dayjs) => void;
}

function CalendarPro(props: CalendarProProps) {
	const { 
        style ,
        className , 
        locale , 
        value,
        onChange
    } = props;
	// 合并类名
	const classNames = classnames("calendar-pro", className);

    // 当前日期
    const [curValue, setCurValue] = useState<Dayjs>(value);
    // 当前月份
    const [ curMonth , setCurMonth ] = useState<Dayjs>(value)

    
    const changeDate = (date:Dayjs) => {
        setCurValue(date);
        setCurMonth(date);
        onChange?.(date);
    }

    // 改变当前选择的日期
    const selectHandler = (date:Dayjs)=> {
        changeDate(date)
    }

    // 上个月
    const prevMonthHandler = () => {
        setCurMonth(curMonth.subtract(1, 'month'));
    }

    
    // 下个月
    const nextMonthHandler = () => {
        setCurMonth(curMonth.add(1, 'month'));
    }

    
    // 回到今天
    const todayHandler = () => {
        const date = dayjs(Date.now());
        changeDate(date)
    }


	return (
		<LocaleContext.Provider value={{
            locale:locale || navigator.language
        }}>
			<div className={classNames} style={style}>
				<Header 
                    curMonth={curMonth}
                    prevMonthHandler={prevMonthHandler}
                    nextMonthHandler={nextMonthHandler}
                    todayHandler={todayHandler}
                />
				<MonthCalendar 
                    {...props} 
                    value={curValue}
                    curMonth={curMonth}
                    selectHandler={selectHandler}
                />
			</div>
		</LocaleContext.Provider>
	);
}

export default CalendarPro;
